package com.daxia.bumall.web.controller;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.daxia.bumall.common.AdType;
import com.daxia.bumall.common.DesignOrderType;
import com.daxia.bumall.common.Logs;
import com.daxia.bumall.common.RecommonStatus;
import com.daxia.bumall.common.UserDesignStatus;
import com.daxia.bumall.common.UserType;
import com.daxia.bumall.dto.BrandDTO;
import com.daxia.bumall.dto.CityDTO;
import com.daxia.bumall.dto.CommunityDTO;
import com.daxia.bumall.dto.CommunityHouseTypeDTO;
import com.daxia.bumall.dto.DesignDTO;
import com.daxia.bumall.dto.DesignProductDTO;
import com.daxia.bumall.dto.DesignerDTO;
import com.daxia.bumall.dto.DistrictDTO;
import com.daxia.bumall.dto.GPSAddressDTO;
import com.daxia.bumall.dto.HouseStyleDTO;
import com.daxia.bumall.dto.OrderDesignerDTO;
import com.daxia.bumall.dto.ProductDTO;
import com.daxia.bumall.dto.SpaceDTO;
import com.daxia.bumall.dto.SpaceObjectDTO;
import com.daxia.bumall.dto.SpecificationDTO;
import com.daxia.bumall.dto.UserDesignDTO;
import com.daxia.bumall.dto.UserDesignDetailDTO;
import com.daxia.bumall.model.Brand;
import com.daxia.bumall.model.City;
import com.daxia.bumall.model.Community;
import com.daxia.bumall.model.Design;
import com.daxia.bumall.model.Designer;
import com.daxia.bumall.model.District;
import com.daxia.bumall.model.HouseStyle;
import com.daxia.bumall.model.HouseType;
import com.daxia.bumall.model.Product;
import com.daxia.bumall.model.ProductProperties;
import com.daxia.bumall.model.SpaceObject;
import com.daxia.bumall.model.Specification;
import com.daxia.bumall.model.User;
import com.daxia.bumall.model.UserDesign;
import com.daxia.bumall.support.Page;

@Controller
@RequestMapping("design")
public class DesignController extends BaseController { 
	
	@RequestMapping("index")
	public String index(Map<String, Object> map, Page page,Long cityId,Long districtId,Long communityId,Long communityHouseTypeId,Long houseStyleId,HttpServletRequest request) throws Exception {
		GPSAddressDTO gpsAddress = null;
		if(cityId == null) {
			//String ip = getIpAddress(request);
			String ip = request.getRemoteHost(); 
			gpsAddress = locationService.getGPSAddressByIP(ip);
			if(gpsAddress == null) {  //当前用户所在位置
				gpsAddress = locationService.getDefaultAddress();
			}
			//cityId = gpsAddress.getCity().getId();
		} else {
			CityDTO cityDTO = new CityDTO();
			cityDTO.setId(cityId);
			cityDTO = cityService.findOne(cityDTO);
			gpsAddress = new GPSAddressDTO();
			gpsAddress.setCity(cityDTO);
			gpsAddress.setProvince(cityDTO.getProvince());
		}
		if(districtId == null) {
			//districtId = gpsAddress.getDistrict().getId();
		}
		
		map.put("menuType",2);
		map.put("gpsAddress", gpsAddress);
		map.put("cityId",cityId);
		map.put("districtId",districtId);
		map.put("houseStyleId",houseStyleId);
		map.put("communityId",communityId);
		map.put("communityHouseTypeId",communityHouseTypeId);
		getShowCategories(map);
		CommunityHouseTypeDTO queryDto = getHouseTypeQuery(cityId, districtId, communityId, communityHouseTypeId,houseStyleId);   //根据传入的条件将对应的数据加载
		List<CommunityHouseTypeDTO> communityHouseTypes = communityHouseTypeService.find2(queryDto, page);
		map.put("communityHouseTypes", communityHouseTypes);
		for (CommunityHouseTypeDTO communityHouseTypeDTO : communityHouseTypes) {
			if(houseStyleId != null) {  //如果设定了设计类型，就要传入设计类型
				CommunityHouseTypeDTO houseType = new CommunityHouseTypeDTO();
				houseType.setId(communityHouseTypeDTO.getId());
				DesignDTO queryDesign = new DesignDTO();
				queryDesign.setCommunityHouseType(houseType);
				HouseStyleDTO styleDTO = new HouseStyleDTO();
				styleDTO.setId(houseStyleId);
				queryDesign.setHouseStyle(styleDTO);
				communityHouseTypeDTO.setDesigns(designService.find(queryDesign, page));
			} else {
				communityHouseTypeDTO.setDesigns(designService.findByCommunityHouseType(communityHouseTypeDTO.getId(), new Page()));
			}
		}
		//运营商城市和地区列表
		List<CityDTO> operCities = cityService.getCitysFromUserType(UserType.City.getValue()); 
		map.put("cities",operCities);
		CityDTO chooseCity = null;
		if(cityId != null) {   //如果选中了城市，就拿出该城市内容
			CityDTO city = new CityDTO();
			city.setId(cityId);
			chooseCity = city;
		} else {
			if(operCities.size() > 0) {
				CityDTO firstCity = operCities.get(0);
				chooseCity = firstCity;
			}
		}
		//地区列表
		DistrictDTO dis = new DistrictDTO();
		dis.setCity(chooseCity);
		List<DistrictDTO> districts = null;
		if (chooseCity != null) {
			districts = districtService.find(dis, null);
		}
		map.put("districts",districts);
		//所在城市楼盘
		DistrictDTO chooseDistrict = null;
		if(districtId != null) {  //如果选择了区域，就要将该区域的全部拿到
			DistrictDTO district = new DistrictDTO();
			district.setId(districtId);
			chooseDistrict = district;
		} else {
			/*if(districts != null) {
				chooseDistrict = districts.get(0);
			}*/
		}
		map.put("ads", adService.findByType(AdType.DesignModel));
		List<CommunityDTO> communities = new Vector<CommunityDTO>();   
		CommunityDTO queryCommunity = new CommunityDTO();
		if(chooseDistrict != null) {
			queryCommunity.setDistrict(chooseDistrict);
		}
		if(cityId != null) {
			queryCommunity.setCity(chooseCity);
		}
		communities = communityService.find(queryCommunity, null);
		map.put("communities",communities);
		//户型
		map.put("provinces", provinceService.findAll());
		map.put("houseStyles", houseStyleService.findAll());
		map.put("page", page);
		
		List<DesignerDTO> designers = designerService.findAll();
		for (DesignerDTO d : designers) {
		}
		map.put("designers", designers);
		return "design/design_index";
	}
	
	 public final static String getIpAddress(HttpServletRequest request) throws IOException {  
	        // 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址  
	  
	        String ip = request.getHeader("X-Forwarded-For");   
	        Logs.COMMON.debug("ip = " +ip); 
	  
	        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	                ip = request.getHeader("Proxy-Client-IP");  
	            }  
	            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	                ip = request.getHeader("WL-Proxy-Client-IP");  
	            }  
	            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	                ip = request.getHeader("HTTP_CLIENT_IP");  
	            }  
	            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	                ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
	            }  
	            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	                ip = request.getRemoteAddr();  
	            }   
	        }
	        if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
	            try {
	            	Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
	            	InetAddress ipNet = null;
	            	while (allNetInterfaces.hasMoreElements()) {
		            	NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
		            	Enumeration addresses = netInterface.getInetAddresses();
		            	while (addresses.hasMoreElements()) {
		            		ipNet = (InetAddress) addresses.nextElement();
			            	if (ipNet != null && ipNet instanceof Inet4Address) {
			            			ip = ipNet.getHostAddress();
			            	} 
		            	}
	            	}
	            }
	            catch (Exception e) {
	            }
	        }
	        return ip;  
	    }  
	
	public CommunityHouseTypeDTO getHouseTypeQuery(Long cityId,Long districtId,Long communityId,Long communityHouseTypeId,Long houseStyleId) {
		CommunityHouseTypeDTO dto = new CommunityHouseTypeDTO();
		if(communityHouseTypeId != null) {
			dto.setId(communityHouseTypeId);
		}
		if(houseStyleId != null) {
			HouseStyleDTO houseStyle = new HouseStyleDTO();
			houseStyle.setId(houseStyleId);
			dto.setHouseStyle(houseStyle);
		}
		if(cityId != null || districtId != null || communityId != null) {
			CommunityDTO community = new CommunityDTO();
			if(cityId != null) {
				CityDTO city = new CityDTO();
				city.setId(cityId);
				community.setCity(city);
			}
			if(districtId != null) {
				DistrictDTO district = new DistrictDTO();
				district.setId(districtId);
				community.setDistrict(district);
			}
			if(communityId != null) {
				community.setId(communityId);
			}
			dto.setCommunity(community);
		}
		return dto;
	}
	
	@RequestMapping("list")
	public String list() throws Exception {
		return "design/design_list";
	}
	
	@ResponseBody
    @RequestMapping("findCommunityByCity")
    public String findCommunityByCity(Long cityId) throws Exception {
		CommunityDTO query = new CommunityDTO();
		query.setCity(new City());
		query.getCity().setId(cityId);
		
		List<CommunityDTO> communities = communityService.find(query, null);
		
        JSONArray array = new JSONArray();
        for (CommunityDTO d : communities) {
            JSONObject json = new JSONObject();
            json.put("id", d.getId());
            json.put("name", d.getName());
            array.add(json);
        }
        return array.toJSONString();
    }
	
	@RequestMapping("designerOrder")
	public String designerOrder(Long userId,Map<String, Object> map) throws Exception {
		map.put("userId", userId);
		if(userId != null) {
			User user = new User();
			user.setId(userId);
			DesignerDTO designer = new DesignerDTO();
			designer.setUser(user);
			designer = designerService.findOne(designer);
			map.put("designer", designer);
		}
		return "design/design_desgnerOrder";
	}
	
	@ResponseBody
    @RequestMapping("orderDesigner")
    public String orderDesigner(String name, String mobile, Long provinceId, Long cityId, Long communityId,Long designerId) throws Exception {
		if ("姓名".equals(name)) {
			name = "";
		}
		if ("手机号".equals(mobile)) {
			mobile = "";
		}
		assertTrue(StringUtils.isNotBlank(name), "请填写姓名");
		assertTrue(StringUtils.isNotBlank(mobile), "请填写手机号码");
		assertTrue(provinceId != null, "请填写手机号码");
		assertTrue(cityId != null, "请填写手机号码");
		
		OrderDesignerDTO dto = new OrderDesignerDTO();
		if(designerId != null) {
			Designer designer = new Designer();
			designer.setId(designerId);
			dto.setDesigner(designer);
		}
		dto.setUser(getCurrentUserDTO());
		dto.setArea(null);
		if (cityId != null) {
			dto.setCity(new City());
			dto.getCity().setId(cityId);
		}
		if (communityId != null) {
			CommunityDTO communityDTO = communityService.load(communityId);
			dto.setCommunity(communityDTO);
			dto.setCommunityName(communityDTO.getName());
		}
		dto.setCreateTime(new Date());
		dto.setHouseStyle(null);
		dto.setHouseType(null);
		dto.setOrderTime(null);
		dto.setOrderName(name);
		dto.setOrderMobile(mobile);
		orderDesignerService.create(dto);
        return okJson();
    }
	
	@RequestMapping("listByCommunityHouseType")
	public String listByCommunityHouseType(Long id, Map<String, Object> map,Page page) throws Exception {
		CommunityHouseTypeDTO n = communityHouseTypeService.load(id);
		n.setDesigns(designService.findByCommunityHouseType(id, new Page()));
		getShowCategories(map);
		map.put("page", page);
		map.put("n", n);
		return "design/design_listByCommunityHouseType";
	}
	
	@RequestMapping("detail")
	public String detail(Long id, Map<String, Object> map) throws Exception {
		DesignDTO n = designService.load(id);
		getShowCategories(map);
		map.put("d", n);
		map.put("designs", designService.find(new DesignDTO(), new Page()));
		DesignProductDTO dp = new DesignProductDTO();
		Design query = new Design();
		query.setId(id);
		dp.setDesign(query); 
		List<DesignProductDTO> dps = designProductService.find(dp, null);
		List<Product> products = new Vector<Product>();
		Double totalCount = 0d;
		if(dps != null && dps.size() > 0) {
			for(DesignProductDTO dto:dps) {
				Product product = dto.getProduct();
				products.add(product);
				totalCount += dto.getSpecification().getRealPrice();
			}
		}
		map.put("totalCount", totalCount);
		map.put("designProducts",dps);
		return "design/design_detail"; 
	}
	
	@RequestMapping("detailNew")
	public String detailNew(Long id, Map<String, Object> map) throws Exception {
		prepareCategories(map);
		DesignDTO design = designService.load(id);
		map.put("design", design);
		
		DesignDTO qy=new DesignDTO();  //推荐方案
		qy.setRecommend(RecommonStatus.Recommened.getValue());
		map.put("designs", designService.find(qy, new Page()));
		
		DesignProductDTO dp = new DesignProductDTO();
		Design query = new Design();
		query.setId(id);
		dp.setDesign(query); 
		List<DesignProductDTO> designProducts = designProductService.find(dp, null);
		map.put("designProducts",designProducts);
		map.put("provinces", provinceService.findAll());
		return "design_new/design_detail"; 
	}
	/**
	 * 客户自选方案详情
	 * @param id
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("detailChoice")
	public String detailChoice(Long id, Map<String, Object> map) throws Exception {
		prepareCategories(map);
		UserDesignDTO design=userDesignService.load(id);
		map.put("design", design);
		
		CommunityHouseTypeDTO com=new CommunityHouseTypeDTO();
		Community community=new Community();
		community.setId(design.getCommunity().getId());
		HouseType houseType=new HouseType();
		houseType.setId(design.getHouseType().getId());
		
		com.setCommunity(community);
		com.setHouseType(houseType);
		CommunityHouseTypeDTO communityHouseTypeDTO=communityHouseTypeService.findOne(com);
		map.put("communityHouseTypeDTO", communityHouseTypeDTO);
		
		UserDesignDetailDTO query=new UserDesignDetailDTO();
		query.setUserDesign(design);
		
		map.put("designProducts",userDesignDetailService.find(query,null));
		
		return "design_new/design_detail_choice"; 
	}
	
	
	
	@RequestMapping("designer")
	public String designer(Long id, Long userId,Map<String, Object> map,Page page) throws Exception {
		DesignerDTO n = designerService.load(id);
		getShowCategories(map);
		map.put("n", n);
		map.put("designs", designService.find(new DesignDTO(), page));
		map.put("page", page);
		return "design/design_designer";
	}

	/**
	 * 设计方案列表
	 * @param map
	 * @param page
	 * @param cityId
	 * @param districtId
	 * @param communityId
	 * @param houseStyleId
	 * @param area
	 * @param houseTypeId
	 * @param orderType
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("indexNew")
	public String indexNew(Map<String, Object> map, Page page,Long cityId,Long districtId,Long communityId,Long houseStyleId,Integer area,Long houseTypeId,Integer orderType,HttpServletRequest request) throws Exception {
		prepareCategories(map);
		map.put("cityId",cityId);  //城市
		map.put("districtId",districtId);	//地区
		map.put("communityId",communityId);	//楼盘
		map.put("houseStyleId",houseStyleId);	//风格
		map.put("area",area);	//面积
		map.put("houseTypeId",houseTypeId);	//户型
		map.put("orderType",orderType);	//排序规则
		
		page.setPageSize(8);
		List<CityDTO> citys=cityService.findCitysByCommunity();
		map.put("citys", citys);
		if(cityId==null){ //默认
			if(citys!=null&&citys.size()>0){
				//CityDTO ct=citys.get(0);
				//List<DistrictDTO> districts=districtService.findByCity(ct.getId());
				//map.put("districts", districts);
			}
			//map.put("communities",communityService.findAll());
		}else{//选择了城市
			List<DistrictDTO> districts=districtService.findByCity(cityId);
			map.put("districts", districts);
			if(districtId==null){
				map.put("communities",communityService.findByCityId(cityId));
			}else{//选择了区域
				map.put("communities",communityService.findByCityAndDistrictId(cityId,districtId));
			}
		}
		map.put("houseStyles", houseStyleService.findAll());
		map.put("houseTypes", houseTypeService.findAll());
		
		map.put("designs", designService.find(createQuery(cityId, districtId, communityId, houseStyleId, area, houseTypeId,orderType), page));
		map.put("page", page);
		
		return "design_new/design_index";
	}
	/**
	 * 客户自选方案
	 * @param map
	 * @param page
	 * @param communityId
	 * @param houseStyleId
	 * @param area
	 * @param houseTypeId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("choice")
	public String choice(Map<String, Object> map, Page page,Long communityId,Long houseStyleId,Integer area,Long houseTypeId,HttpServletRequest request) throws Exception {
		prepareCategories(map);
		map.put("communityId",communityId);	//楼盘
		map.put("houseStyleId",houseStyleId);	//风格
		map.put("area",area);	//面积
		map.put("houseTypeId",houseTypeId);	//户型
		
		page.setPageSize(6);
		List<CityDTO> citys=cityService.findCitysByCommunity();
		map.put("citys", citys);
		map.put("communities",communityService.findAll());
		map.put("houseStyles", houseStyleService.findAll());
		map.put("houseTypes", houseTypeService.findAll());
		
		UserDesignDTO query=new UserDesignDTO();
		if(communityId!=null){
			Community community=new Community();
			community.setId(communityId);
			query.setCommunity(community);
		}
		if(houseStyleId!=null){
			HouseStyle houseStyle=new HouseStyle();
			houseStyle.setId(houseStyleId);
			query.setHouseStyle(houseStyle);
		}
		if(houseTypeId!=null){
			HouseType houseType=new HouseType();
			houseType.setId(houseTypeId);
			query.setHouseType(houseType);
		}
		if(area!=null&&area!=0){
			query.setHouseAreaTag(area);
		}
		map.put("designs", userDesignService.find(query, page));
		map.put("page", page);
		
		return "design_new/design_choice";
	}
	/**
	 * 创建设计方案查询条件
	 * @param cityId
	 * @param districtId
	 * @param communityId
	 * @param houseStyleId
	 * @param area
	 * @param houseTypeId
	 * @param orderType
	 * @return
	 */
	private DesignDTO createQuery(Long cityId,Long districtId,Long communityId,Long houseStyleId,Integer area,Long houseTypeId,Integer orderType){
		DesignDTO query=new DesignDTO();
		Community community =new Community();
		community.setId(communityId);
		if(cityId!=null){
			City city=new City();
			city.setId(cityId);
			community.setCity(city);
		}
		if(districtId!=null){
			District district=new District();
			district.setId(districtId);
			community.setDistrict(district);
		}
		query.setCommunity(community);
		if(houseStyleId!=null){
			HouseStyle houseStyle=new HouseStyle();
			houseStyle.setId(houseStyleId);
			query.setHouseStyle(houseStyle);
		}
		if(area!=null){
			query.setHouseAreaTag(area);
		}
		if(houseTypeId!=null){
			HouseType houseType=new HouseType();
			houseType.setId(houseTypeId);
			query.setHouseType(houseType);
		}
		if(orderType!=null){
			query.setOrderType(DesignOrderType.getByValue(orderType));
		}		
		return query;
	}

	
	/**
	 * 在线设计
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("online")
	public String online(Map<String, Object> map) throws Exception {
		prepareCategories(map);
		map.put("communityList", communityService.findAll());
		map.put("houseStyles", houseStyleService.findAll());
		return "design/design_online";
	}
	
	@RequestMapping("online2")
	public String online2(Long communityId, Long houseTypeId, Long houseStyleId, String houseStyleImage, Map<String, Object> map) throws Exception {
		prepareCategories(map);
		map.put("c", communityService.load(communityId));
		map.put("ht", houseTypeService.load(houseTypeId));
		map.put("hs", houseStyleService.load(houseStyleId));
		map.put("houseStyleImage", houseStyleImage);
		
		map.put("brands", brandService.findRecommended());
		map.put("houseStyles", houseStyleService.findAll());
		return "design/design_online2";
	}
	
	@ResponseBody
	@RequestMapping("getHouseType")
	public String getHouseType(Long id, Map<String, Object> map) throws Exception {
		JSONArray array = new JSONArray();
		List<CommunityHouseTypeDTO> houseTypes = communityHouseTypeService.findHouseTypes(id);
		for (CommunityHouseTypeDTO d : houseTypes) {
			JSONObject json = new JSONObject();
			json.put("houseTypeId", d.getHouseType().getId());
			json.put("name", d.getHouseType().getName());
			json.put("image", d.getImage());
			array.add(json);
		}
		return ok(array);
	}
	
	/**
	 * 
	 * @param id houseStyleId
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("getHouseStyleImages")
	public String getHouseStyleImages(Long id, Map<String, Object> map) throws Exception {
		HouseStyleDTO s = houseStyleService.load(id);
		JSONArray array = new JSONArray();
		if (StringUtils.isNotBlank(s.getImages())) {
			String[] arr = s.getImages().split(",");
			for (String string : arr) {
				JSONObject json = new JSONObject();
				json.put("name", s.getName());
				json.put("image", string);
				array.add(json);
			}
		}
		
		return ok(array);
	}
	
	@ResponseBody
	@RequestMapping("getSpaces")
	public String getSpaces() throws Exception {
		List<SpaceDTO> spaces = spaceService.findAll();
		JSONArray a1 = new JSONArray();
		for (SpaceDTO s : spaces) {
			JSONObject j1 = new JSONObject();
			j1.put("id", s.getId());
			j1.put("name", s.getName());
			j1.put("show", true);
			JSONArray a2 = new JSONArray();
			for (SpaceObject so : s.getObjects()) {
				JSONObject j2 = new JSONObject();
				j2.put("type", so.getName());
				j2.put("img", so.getImage());
				j2.put("defaultImg", so.getImage());
				j2.put("count", 0);
				j2.put("id", so.getId());
				j2.put("defaultId", so.getId());
				j2.put("name", so.getName());
				j2.put("defaultName", so.getName());
				j2.put("price", 0);
				j2.put("parentName", s.getName());
				a2.add(j2);
			}
			j1.put("items", a2);
			a1.add(j1);
		}
		
		return a1.toJSONString();
	}
	
	@ResponseBody
	@RequestMapping("getProducts")
	public String getProducts(Long brandId, Double startPrice, Double endPrice, Page page, String searchTerm, String orderBy, String style) throws Exception {
		ProductDTO query = new ProductDTO();
		query.setSearchTerm(searchTerm);
		if (brandId != null) {
			query.setBrand(new Brand());
			query.getBrand().setId(brandId);
		}
		query.setStartPrice(startPrice);
		query.setEndPrice(endPrice);
		query.setOrderBy(orderBy);
		if (StringUtils.isNotBlank(style)) {
			query.setStyle(style.replace("风格", ""));
		}
		
		List<ProductDTO> products = productService.findForOnlineDesign(query, page);
		JSONObject json = new JSONObject();
		json.put("totalRecords", page.getTotalRecords());
		json.put("totalPages", page.getTotalPages());
		JSONArray array = new JSONArray();
		for (ProductDTO p : products) {
			JSONObject jP = new JSONObject();
			jP.put("name", p.getName());
			jP.put("id", p.getId());
			jP.put("image", p.getFirstSpec().getImages().split(",")[0]);
			JSONArray specArr = new JSONArray();
			for (Specification sp : p.getSpecifications()) {
				JSONObject j = new JSONObject();
				j.put("id", sp.getId());
				j.put("ogCode", sp.getOgCode());
				j.put("spec1", sp.getSpec1());
				j.put("spec2", sp.getSpec2());
				j.put("image", sp.getImages().split(",")[0]);
				j.put("realPrice", sp.getRealPrice());
				for (ProductProperties pp : sp.getProductProperties()) {
					if ("风格".equals(pp.getName())) {
						j.put("style", pp.getValue());
					}
					if ("材质".equals(pp.getName())) {
						j.put("material", pp.getValue());
					}
					if ("颜色".equals(pp.getName())) {
						j.put("color", pp.getValue());
					}
				}
				specArr.add(j);
			}
			jP.put("specs", specArr);
			jP.put("specIndex", 0);
			array.add(jP);
		}
		json.put("data", array);
		return json.toJSONString();
	}
	
	@ResponseBody
	@RequestMapping("getBrands")
	public String getBrands() throws Exception {
		List<BrandDTO> brands = brandService.findRecommended();
		JSONArray array = new JSONArray();
		for (BrandDTO b : brands) {
			JSONObject j = new JSONObject();
			j.put("name", b.getName());
			j.put("id", b.getId());
			array.add(j);
		}
		return array.toJSONString();
	}
	
	/**
	 * 
	 * @param communityId
	 * @param houseTypeId
	 * @param houseStyleId
	 * @param houseStyleImage
	 * @param name
	 * @param area
	 * @param specs 123-1-1,456-2-1, (specification-count-spaceObjectId)
	 * @return
	 * @throws Exception
	 */
	@Transactional
	@ResponseBody
	@RequestMapping("saveDesign")
	public String saveDesign(Long communityId, Long houseTypeId, Long houseStyleId, String houseStyleImage, String name, String area, String specs, boolean publish) throws Exception {
		UserDesignDTO ud = new UserDesignDTO();
		ud.setArea(area);
		ud.setCommunity(new Community());
		ud.getCommunity().setId(communityId);
		ud.setCreateTime(new Date());
		ud.setHeadImage(houseStyleImage);
		ud.setHouseStyle(new HouseStyle());
		ud.getHouseStyle().setId(houseStyleId);
		ud.setHouseType(new HouseType());
		ud.getHouseType().setId(houseTypeId);
		ud.setName(name);
		//if (publish) {
			ud.setStatus(UserDesignStatus.NotAudit.getValue());
		//} else {
			//ud.setStatus(UserDesignStatus.New.getValue());
		//}
		ud.setTotalPrice(0d);
		ud.setUser(getCurrentUserDTO());
		Long udId = userDesignService.create(ud);
		
		String[] arr = specs.split(",");
		double totalPrice = 0;
		for (String string : arr) {
			String[] arr2 = string.split("-");
			Long specId = Long.parseLong(arr2[0]);
			int count = Integer.parseInt(arr2[1]);
			Long spaceObjectId = Long.parseLong(arr2[2]);
			SpecificationDTO s = specificationService.load(specId);
			SpaceObjectDTO so = spaceObjectService.load(spaceObjectId);
			UserDesignDetailDTO dd = new UserDesignDetailDTO();
			dd.setCount(count);
			dd.setProduct(s.getProduct());
			dd.setSpace(so.getSpace());
			dd.setSpaceObject(so);
			dd.setSpecification(s);
			dd.setUserDesign(new UserDesign(udId));
			userDesignDetailService.create(dd);
			totalPrice += s.getRealPrice();
		}
		ud = userDesignService.load(udId);
		ud.setTotalPrice(totalPrice);
		userDesignService.updateAllFields(ud);
		return ok();
	}
}	
